package com.example.yt_app.Fragment.EquipmentFragment;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yt_app.Activity.AddDevice;
import com.example.yt_app.Activity.Device.LedActivity;
import com.example.yt_app.Activity.SetActivity;
import com.example.yt_app.Activity.SpeekActivity;
import com.example.yt_app.Fragment.BaseFragment.BaseFragment;
import com.example.yt_app.Interface.SB_HttpBinService;
import com.example.yt_app.R;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.SB_Parameter;
import com.example.yt_app.Urils.SPTool;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.example.yt_app.adapter.RecyclerViewAdapter;
import com.example.yt_app.bean.Onenet.Data;
import com.example.yt_app.bean.Onenet.JsonRootBean;
import com.example.yt_app.bean.Onenet_online.Devices;
import com.example.yt_app.bean.Onenet_online.Online_json;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OSUtils;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.recyclerview.adapters.AnimationAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by dell on 2021/7/22.
 */
@SuppressWarnings("ALL")
public class HomeSbFragment extends BaseFragment {

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.rv)
    RecyclerView mRecyclerView;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    private AnimationAdapter mAnimationAdapter;
    //要显示的数据
    private OkHttpClient okHttpClient;
    private RecyclerViewAdapter mRecyclerViewAdapter;
    private final mHandler mHandler = new mHandler();
    int time;
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    int DelateList;
    private static int sum;
    private final ArrayList<Map<String, Object>>list = new ArrayList<>();
    Map<String, Object>map;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_sb;
    }
    private static int counter = 0;

    @Override
    protected void initView() {

        /**----------------设置 RecyclerView -----------------**/
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false);
        //设置默认动画
        DefaultItemAnimator animator = new DefaultItemAnimator();
        //设置动画时间
        animator.setAddDuration(1000);
        animator.setChangeDuration(1000);
        animator.setMoveDuration(1000);
        animator.setRemoveDuration(800);
        mRecyclerView.setItemAnimator(animator);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        /**-------------------------------------------------**/
        mRecyclerViewAdapter = new RecyclerViewAdapter(getActivity(), list);
        mRecyclerView.setAdapter(mRecyclerViewAdapter);
        //设置 Header 为 贝塞尔雷达 样式
        // refreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));
        //设置 Footer 为 球脉冲 样式
        //  refreshLayout.setRefreshFooter(new BallPulseFooter(getActivity()).setSpinnerStyle(SpinnerStyle.Scale));
        /*网络请求*/
        okHttpClient = new OkHttpClient();
        //添加点击效果
        //mAnimationAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);

        mRecyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.onItemClickListener() {
            Integer[] widthAndHeight = Utils.getWidthAndHeight(getActivity().getWindow());
            @Override
            public void onItemClick(View view, int position) {
                if (list.get(position).get("id").toString() !="请刷新"||list.get(position).get("name").toString() !="请刷新"){
                    //Toast.makeText(getContext(), "你长按了-》" + list.get(position), Toast.LENGTH_SHORT).show();
                    Intent i= new Intent(getActivity(),LedActivity.class);
                    i.putExtra("id",list.get(position).get("id").toString());
                    i.putExtra("name",list.get(position).get("name").toString());
                    i.putExtra("online",list.get(position).get("online").toString());
                    startActivity(i);
                }else{
                    showMessage("暂无设备");
                }

            }

            @Override
            public void onItemLongClick(View view, int position) {
                //Toast.makeText(getContext(), "你长按了-》" + list.get(position), Toast.LENGTH_SHORT).show();
                DelateList = position;
                sum = SB_Parameter.HomeSUM;
                //showPopup(Gravity.BOTTOM, ViewGroup.LayoutParams.MATCH_PARENT, widthAndHeight[1] / 2, R.style.BottomAnimation);
                showPopup(Gravity.NO_GRAVITY, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, R.style.RightAnimation);

            }
        });

    }
    @Override
    protected void initData(){
        State.DeviceIDHome = SPTool.getInstance(getContext()).getString("DeviceIDHome","");

    }
    /**
     * 重新被调用的时候运行
     * */
//    @Override
//    public void onStart () {
//        super.onStart ();
//        String id = State.DeviceIDHome;
//        System.out.println(id);
//        State.DeviceIDHome = SPTool.getInstance(getContext()).getString("DeviceIDHome","");
//        if (State.DeviceIDHome != id){
//            RxAsync();
//        }
//    }
    @Override
    protected void setListener() {
        //上拉加载底部view设置
        LoadingView loadingView = new LoadingView(getContext());
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                State.DeviceIDHome = SPTool.getInstance(getContext()).getString("DeviceIDHome","");
                if (State.DeviceIDHome != ""){
                    RxAsync();
                    refreshlayout.finishRefresh(1500/*,false*/);//传入false表示刷新失败
                }else {
                    refreshlayout.finishRefresh(false);//传入false表示刷新失败
                    showMessage("暂无设备\n下滑添加");
                }
            }
        });

    }
    @OnClick({R.id.action_a,R.id.action_b,R.id.action_c})
    public void onClick(View v) {
        switch (v.getId()){
            /**
             *  设置三个悬浮按钮的监听事件
             * */
            case R.id.action_a:
                State.SCENE = "Home";
                startActivity(new Intent(getActivity(), AddDevice.class));
                break;
            case R.id.action_b:
                startActivity(new Intent(getActivity(), SpeekActivity.class));
                break;
            case R.id.action_c:
                showMessage("c");
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }


    @SuppressWarnings("AliDeprecation")
    @SuppressLint("HandlerLeak")
    private class mHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

//
                default:break;
            }
        }
    }

    /**
     * TODO RX思维
     *  获取设备状态
     */
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void RxAsync(){

        //步骤4：创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.heclouds.com/") // 设置 网络请求 Url
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        // 步骤5：创建 网络请求接口 的实例
        SB_HttpBinService request = retrofit.create(SB_HttpBinService.class);
        // 步骤6：采用Observable<...>形式 对 网络请求 进行封装
        Observable<Online_json> observable = request.getMessage(State.ApiKey,State.DeviceIDHome);
        // 步骤7：发送网络请求
        observable.subscribeOn(Schedulers.io())               // 在IO线程进行网络请求
                .observeOn(AndroidSchedulers.mainThread())  // 回到主线程 处理请求结果
                .subscribe(new Observer<Online_json>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.d("TAG", "开始采用subscribe连接");
                    }

                    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
                    @Override
                    public void onNext(@NotNull Online_json online_json) {

                        List<Devices> devices = online_json.getData().getDevices();
                        //Log.d("TAG", responseData);
//                        if (SB_Parameter.All){
                            String o;
                            if (SB_Parameter.HomeSUM < online_json.getData().getTotal_count()){
                                int j;
                                j=online_json.getData().getTotal_count()-SB_Parameter.HomeSUM ;

                                for (int i = 0; i < j; i++) {
                                    map = new HashMap<>();
                                    map.put("id", "请刷新");
                                    map.put("name","请刷新");
                                    map.put("online","请刷新");
                                    list.add(map);
                                }
                                SB_Parameter.HomeSUM = online_json.getData().getTotal_count();
                            }

                            for (int i = 0 ;i<online_json.getData().getTotal_count();i++){
                                if (devices.get(i).getOnline()){

                                    o = "√";
                                }else {
                                    o = "×";
                                }
                                map = list.get(i);
                                map.put("id",  devices.get(i).getId());
                                map.put("name",  devices.get(i).getTitle());
                                map.put("online", o);
                            }
//                        }
//                        else {
//                            SB_Parameter.HomeSUM = online_json.getData().getTotal_count();
//                            SB_Parameter.All = true;
//                            for (int i = 0; i < SB_Parameter.HomeSUM; i++) {
//                                map = new HashMap<>();
//                                map.put("id", "请刷新");
//                                map.put("name","请刷新");
//                                map.put("online","请刷新");
//                                list.add(map);
//                            }
//                        }
                        mRecyclerView.setAdapter(mRecyclerViewAdapter);
                        Delay.Delay_ms(500);
                        mRecyclerView.setAdapter(mRecyclerViewAdapter);

                    }


                    @Override
                    public void onError(Throwable e) {
                        Log.d("TAG," ,"请求失败");
                    }

                    @Override
                    public void onComplete() {
                        Log.d("TAG", "请求成功");
                    }
                });
    }

    private View mPopupView;
    private PopupWindow mPopupWindow;
    private int mCurPosition;
    /**
     * 弹出popupWindow
     * Show popup.
     *
     * @param gravity        the gravity
     * @param width          the width
     * @param height         the height
     * @param animationStyle the animation style
     */
    @SuppressWarnings({"AliDeprecation", "AlibabaLowerCamelCaseVariableNaming"})
    public void showPopup(int gravity, int width, int height, int animationStyle) {

        mPopupView = LayoutInflater.from(mActivity).inflate(R.layout.popup_demo, null);
        mPopupWindow = new PopupWindow(mPopupView, width, height);
        //以下属性响应空白处消失和实体按键返回消失popup
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //沉浸式模式下，以下两个属性并不起作用
        mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //重点，此方法可以让布局延伸到状态栏和导航栏
        mPopupWindow.setClippingEnabled(false);
        //设置动画
        mPopupWindow.setAnimationStyle(animationStyle);
        //弹出
        mPopupWindow.showAtLocation(getActivity().getWindow().getDecorView(), gravity, 0, 0);
        //弹出后背景alpha值
        //backgroundAlpha(0.5f);
        //消失后恢复背景alpha值
        mPopupWindow.setOnDismissListener(() -> backgroundAlpha(1f));
        //适配弹出popup后布局被状态栏和导航栏遮挡问题
        updatePopupView();
        //设置监听器
        TextView take_photo = mPopupView.findViewById(R.id.take_photo);
        TextView from_albums = mPopupView.findViewById(R.id.from_albums);
        LinearLayout cancel = mPopupView.findViewById(R.id.cancel);
        //设置监听器
        TextView sai_id = mPopupView.findViewById(R.id.sai_id);
        TextView sai_name = mPopupView.findViewById(R.id.sai_name);
        TextView sai_phone = mPopupView.findViewById(R.id.sai_phone);
        sai_id.setText(list.get(DelateList).get("id").toString());
        sai_name.setText(list.get(DelateList).get("name").toString());
        sai_phone.setText(list.get(DelateList).get("online").toString());
        if (list.get(DelateList).get("online").toString() == "true"){
            //String o = String.valueOf(devices.get(i).getOnline());
            sai_phone.setTextColor(Color.GREEN);
        }else {
            sai_phone.setTextColor(Color.RED);
        }
        //删除按钮监听
        take_photo.setOnClickListener(v -> {
            if (sum > SB_Parameter.HomeSUM){
                showMessage("该设备已删除，请重新选择");
            }else {
                AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
                builder.setTitle("提示");
                builder.setMessage("是否确定删除该设备？");
                builder.setIcon(R.mipmap.gantanhao);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mRecyclerViewAdapter.Remove(DelateList);
                        SB_Parameter.HomeSUM = SB_Parameter.HomeSUM-1;
                        if (mPopupWindow != null && mPopupWindow.isShowing()) {
                            mPopupWindow.dismiss();
                        }

                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                AlertDialog alertDialog=builder.create();
                alertDialog.show();
            }
        });
        //设置按钮监听
        from_albums.setOnClickListener(v -> {

        });
        //取消按钮监听
        cancel.setOnClickListener(view -> {
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        });
    }
    @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
    public void GetDevice(){
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/" + State.DeviceID )
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    /*response.body().string()中的 (.string)只能使用一次*/
                    Log.i("TAG" , "postAsync" + response.body().string());
                    String responseData = response.body().string();
                    JsonRootBean app = Json.gson.fromJson(responseData, JsonRootBean.class);
                    List<Data> streams = (List<Data>) app.getData();
                    System.out.println(streams.get(0).getUnit_symbol());
                    String wendu = streams.get(0).getCurrent_value()+streams.get(0).getUnit_symbol();


                } catch (IOException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

        });

    }

    /**
     * 调整popupWindow里view的Margins值来适配布局被导航栏遮挡问题，因为要适配横竖屏切换，所以代码有点多
     * Update popup view.
     */
    @SuppressWarnings("AliDeprecation")
    private void updatePopupView() {
        int navigationBarHeight = ImmersionBar.getNavigationBarHeight(this);
        int navigationBarWidth = ImmersionBar.getNavigationBarWidth(this);
        if (mPopupView != null) {
            ImmersionBar.setTitleBar(this, mPopupView.findViewById(R.id.toolbar));
            View rlContent = mPopupView.findViewById(R.id.rlContent);
            mPopupView.post(() -> {
                boolean isPortrait;
                boolean isLandscapeLeft;
                int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
                if (rotation == Surface.ROTATION_90) {
                    isPortrait = false;
                    isLandscapeLeft = true;
                } else if (rotation == Surface.ROTATION_270) {
                    isPortrait = false;
                    isLandscapeLeft = false;
                } else {
                    isPortrait = true;
                    isLandscapeLeft = false;
                }
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) rlContent.getLayoutParams();
                if (isPortrait) {
                    layoutParams.setMargins(0, 0, 0, navigationBarHeight);
                } else {
                    if (isLandscapeLeft) {
                        layoutParams.setMargins(0, 0, navigationBarWidth, 0);
                    } else {
                        if (OSUtils.isEMUI3_x()) {
                            layoutParams.setMargins(0, 0, navigationBarWidth, 0);
                        } else {
                            layoutParams.setMargins(navigationBarWidth, 0, 0, 0);
                        }
                    }
                }
                rlContent.setLayoutParams(layoutParams);
            });
        }
    }

    /**
     * 设置弹出popup，背景alpha值
     *
     * @param bgAlpha 0f - 1f
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

}